package com.example.simplecardbasic.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.example.simplecardbasic.Utils.ResultVOUtil;
import com.example.simplecardbasic.Utils.SmsUtil;
import com.example.simplecardbasic.VO.ResultVO;
import com.example.simplecardbasic.enums.ResultEnum;
import com.example.simplecardbasic.exception.CreditException;
import com.example.simplecardbasic.form.SendSmsForm;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping(value = "/sms")
public class SmsController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @PostMapping("/code")
    public ResultVO getCode(@Valid SendSmsForm smsForm,
                            BindingResult bindingResult) throws ClientException{
        if(bindingResult.hasErrors()) {
            throw new CreditException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        //像消息队列中写入手机号码
//        amqpTemplate.convertAndSend("sms","phone",smsForm.getPhone());
        SmsUtil.sendSms(smsForm.getPhone(), stringRedisTemplate);
        return ResultVOUtil.success();
    }
}
